"""统一响应格式处理"""
from typing import Any, Dict, Optional, Union
from flask import jsonify, Response
from flask_babel import gettext as _

from app.status_codes import StatusCode, HttpStatusCode


class ApiResponse:
    """API 响应格式化器"""
    
    @staticmethod
    def success(
        data: Any = None,
        message: Optional[str] = None,
        code: StatusCode = StatusCode.SUCCESS,
        http_status: int = HttpStatusCode.OK
    ) -> Response:
        """成功响应格式"""
        response_data = {
            "success": True,
            "code": code.code,
            "message": message or _(code.message),
            "data": data
        }
        return jsonify(response_data), http_status
    
    @staticmethod
    def error(
        message: Optional[str] = None,
        code: StatusCode = StatusCode.INTERNAL_ERROR,
        http_status: int = HttpStatusCode.INTERNAL_SERVER_ERROR,
        data: Any = None
    ) -> Response:
        """错误响应格式"""
        response_data = {
            "success": False,
            "code": code.code,
            "message": message or _(code.message),
            "data": data
        }
        return jsonify(response_data), http_status
    
    @staticmethod
    def paginated_success(
        data: Any,
        page: int,
        per_page: int,
        total: int,
        message: Optional[str] = None,
        code: StatusCode = StatusCode.SUCCESS
    ) -> Response:
        """分页成功响应格式"""
        response_data = {
            "success": True,
            "code": code.code,
            "message": message or _(code.message),
            "data": data,
            "pagination": {
                "page": page,
                "per_page": per_page,
                "total": total,
                "pages": (total + per_page - 1) // per_page
            }
        }
        return jsonify(response_data), HttpStatusCode.OK


# 快捷响应函数
def success_response(
    data: Any = None,
    message: Optional[str] = None,
    code: StatusCode = StatusCode.SUCCESS,
    http_status: int = HttpStatusCode.OK
) -> Response:
    """成功响应快捷函数"""
    return ApiResponse.success(data, message, code, http_status)


def error_response(
    message: Optional[str] = None,
    code: StatusCode = StatusCode.INTERNAL_ERROR,
    http_status: int = HttpStatusCode.INTERNAL_SERVER_ERROR,
    data: Any = None
) -> Response:
    """错误响应快捷函数"""
    return ApiResponse.error(message, code, http_status, data)


def paginated_response(
    data: Any,
    page: int,
    per_page: int,
    total: int,
    message: Optional[str] = None,
    code: StatusCode = StatusCode.SUCCESS
) -> Response:
    """分页响应快捷函数"""
    return ApiResponse.paginated_success(data, page, per_page, total, message, code) 